<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 课时进度数据模型
 * 
 * @author 陈蕾
 */
class Model_LessonProgress extends ORM
{
	const TABLE = 'lesson_progress';
	
	/**
	 * 课时进度状态：未学习
	 */
	const STATE_NOT  = 0;
	
	/**
	 * 课时进度状态：正在学习
	 */
	const STATE_ING  = 1;
	
	/**
	 * 课时进度状态：已完成
	 */
	const STATE_DONE = 2;
	
	// Model table information
    protected $_table_name = 'lesson_progress';
    
    // Table primary key and value
	protected $_primary_key  = 'id';
	protected $_primary_val  = 'member_id';
	
	/**
	 * 获取当前学习的课程
	 * 
	 * @param int $member_id  学生ID
	 * @param int $chapter_id 章节ID
	 */
	public static function getCurrent($member_id, $chapter_id)
	{
		$record = DB::select()
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->and_where('chapter_id', '=', $chapter_id)
			->order_by('id', 'DESC')
			->limit(1)
			->execute()
			->current();
		
		if (!$record) {
			return array();
		}
		
		return $record;
	}
	
	/**
	 * 获取课程的学习进度
	 * 
	 * @param int $member_id 学生ID
	 * @param int $chapter_id 章节ID
	 * @return array 课时ID => 进度信息
	 */
	public static function getProfileByMember($member_id, $chapter_id)
	{
		$records = DB::select()
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->and_where('chapter_id', '=', $chapter_id)
			->execute()
			->as_array();
		
		$took_stats = Model_LessonLog::getTookStats($member_id);
		
		$ret = array();
		foreach ($records as $record) {
			$key = $record['lesson_id'];
			$ret[$key] = array(
				'state'          => $record['state'],
				'last_study'     => $record['last_study'],
				'time_took'      => $took_stats[$key],
				'exam_score'     => $record['exam_score']
			);
		}
		
		return $ret;
	}
	
	/**
	 * 获取章节课程的学习统计
	 * 
	 * @param int $member_id 学生ID
	 * @return array 章节ID => 已学课时数量
	 */
	public static function getStats($member_id)
	{
		$records = DB::select('chapter_id', array(DB::expr('COUNT(*)'), 'count'))
			->from(self::TABLE)
			->where('member_id', '=', $member_id)
			->and_where('state', '=', self::STATE_DONE)
			->group_by('chapter_id')
			->execute()
			->as_array();
		
		$count = array();
		foreach ($records as $record) {
			$key = $record['chapter_id'];
			$count[$key] = $record['count'];
		}
		
		return $count;
	}
}